#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QFileDialog>
#include <QMessageBox>

#include "projectdialog.h"
#include "config.h"

MainWindow::MainWindow(
    QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    if(!qCfg->currentProjectPath().isEmpty())
    {
        setWindowTitle(qApp->applicationName()+" "+qCfg->currentProjectPath());
        m_currentProject = Project();
        if(!m_currentProject.load(qCfg->currentProjectPath())) {
            m_currentProject = Project();
        }
    }
    m_tableModel = new TableModel;
    ui->tableView->setModel(m_tableModel);
    m_tableModel->load("test.myt");
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_btnLoadJson_clicked()
{
    auto fileName = QFileDialog::getOpenFileName(this, tr("Load table config file"), qApp->applicationDirPath(), "Table config file(*.myt)");
    if(fileName.isEmpty())
        return;
    if(!m_tableModel->load(fileName, Table::JsonFormat)) {
        QMessageBox::warning(this, tr("Load table config file"), tr("Load table config file fail."));
    }
    else {
        ui->statusbar->showMessage(tr("Load %1 success.").arg(fileName), 3000);
    }
}


void MainWindow::on_btnSaveJson_clicked()
{
    auto fileName = QFileDialog::getSaveFileName(this, tr("Save table data"), qApp->applicationDirPath(), "Table config file(*.myt)");
    if(fileName.isEmpty())
        return;
    if(!m_tableModel->save(fileName, Table::JsonFormat)) {
        QMessageBox::warning(this, tr("Save table config file"), tr("Save table config file fail."));
    }
    else {
        ui->statusbar->showMessage(tr("Save %1 success.").arg(fileName), 3000);
    }
}


void MainWindow::on_btnNewProject_clicked()
{
    Project pro = ProjectDialog::getNewProject();
    if(pro.isValid())
        pro.create();
}

